<template>

    <div class="public-imagry" ref="imagery">

        <!-- 数据上传按钮，数据搜索框 -->
        <div class="option" v-if="!isEmpty">

            <div class="option-container" :class="[ isListView ? 'adaption-list' : 'adaption']">
                <!-- <div class="upload-data" @click="upload">
                    <i class="iconfont icon-upload"></i>
                    <span>上传数据</span>
                </div> -->

                <div class="range">
                    <span @click="changeSortTime">
                        <i class="iconfont" :class="`icon-sort-${sortTime}`"></i> 时间
                    </span>
                    <span @click="changeRangeType">
                        <template v-if="isListView"><i class="iconfont icon-tiling"></i> 平铺</template>
                        <template v-else><i class="iconfont icon-menu"></i> 列表</template>
                    </span>
                </div>

                <div class="search">
                    <input type="text" class="input-search" v-model="search" v-on:keyup.enter="query" placeholder="搜索">
                    <div class="btn-search" @click="query">
                        <i class="iconfont icon-loading icon-spin" v-show="isLoading"></i>
                        <i class="iconfont icon-search" v-show="!isLoading"></i>
                    </div>
                </div>
            </div>
        </div>

        <div class="data-list-container">

            <div v-if="isEmpty" class="no-data">
                <img src="../../../static/img/no-data.png">
                <div class="no-data-tip">您还未上传过数据</div>
                <div class="empty-handler" @click="upload">上传数据</div>
            </div>

            <template v-else>
                    <div class="wrapper-body">
                        <div v-show="isListView" class="list-view-header" :class="[ isListView ? 'adaption-list' : 'adaption']" >
                            <div class="name">数据名称</div>
                            <!-- <div class="data-count">数据量</div> -->
                            <div class="date">上传日期</div>
                            <div class="data-option">操作</div>
                        </div>
                        <g-scrollbar class="data-vertical-scroll" :class="{'with-header': isListView}">
                            <div :class="[ isListView ? 'adaption-list' : 'adaption']">
                                <div class="datas-content">
                                    <ul class="data-view">
                                        <component
                                            v-for="(data,index) in dataList"
                                            :currentMenu="currentMenu"
                                            :is="view"
                                            :dataType="dataType"
                                            type="public"
                                            :isPrivate="false"
                                            :data="data"
                                            :index="index"
                                            :key="data.uid"
                                            v-on:open = "open"
                                            v-on:remove="remove"
                                            v-on:data-preview="preview"
                                            v-on:data-share="share"
                                            v-on:data-store="store"
                                            v-on:set-current-menu="setCurrentMenu"></component>
                                    </ul>

                                    <div class="add-more-wrapper">
                                        <button class="add-more" v-show="hasNext" @click="addMore()" :disabled="isLoading">
                                            <span v-show="!isLoading">
                                                <i class="iconfont icon-flip-down"></i> 加载更多
                                            </span>
                                            <span v-show="isLoading">
                                                <i class="iconfont icon-loading spin"></i> 加载中…
                                            </span>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </g-scrollbar>
                    </div>
            </template>
            
        </div>

        <transition-group name="fade">
            <!-- <div :key="'upload-georeference-container'">
                <slice-upload v-if="openUpload"></slice-upload>
            </div> -->
            <data-preview :key="'preview'" :base-path="basePath" :is-private="false" :dataType="dataType" :previewData="previewData"
                @close-preview="closePreview" v-if="openPreview"></data-preview>
            <!-- <data-share 
                v-if="openShare"
                key='share' 
                :shareData="shareData" 
                :groups="groups"
                v-on:close-share="closeShare"
                :shareDataName="shareDataName"></data-share> -->
        </transition-group>

    </div>

</template>

<script>

import Bus from '@/utils/event_bus'
import TilingWrapper from './tiling-wrapper'
import ListWrapper from './list-wrapper'
import ImageryTilingWrapper from './imagery-tiling-wrapper'
import ImageryListWrapper from './imagery-list-wrapper'
import DataPreview from 'components/preview/data-preview'
import GScrollbar from 'components/common/g-scrollbar'
// import Upload from 'components/upload/upload'slice-upload
// import SliceUpload from 'components/upload/slice-upload'
import Georeference from './georeference'
import DataShare from './data-share'
import GButton from '@/components/common/g-button'
import {publicImagery as publicImageryAPI, organization as orgAPI, bookmark as bookmarkAPI} from '@/api'

const viewTypes = ['map', 'table', 'metadata'];
const limit = 60;

export default {

    name: 'public-imagery',

    components:{
        ImageryTilingWrapper,
        ImageryListWrapper,
        ListWrapper,
        TilingWrapper,
        DataPreview,
        // SliceUpload,
        Georeference,
        DataShare,
        GButton,
        GScrollbar
    },

    data: function() {
        const dataType = 'imagery';
        return {
            dataType,
            isLoading: false,
            dataList: [],
            page: 0,
            hasNext: false,
            search: '',
            previewData: null,
            openPreview: false,
            openUpload: false,
            shareData: '',
            shareDataName: '',  //数据名称有可能已经更改，再未刷新数据列表之前，要传入改过的数据名
            openShare: false,
            currentMenu: '',  //用于控制dataWrapper中打开的菜单
            dataUid: null,

            isEmpty: false,
            sortTime: 'desc',
            view: 'imagery-tiling-wrapper',
            groups: [],
            basePath:'/data/public-imagry',

        }
    },

    created: function () {
        // 检查URL中是否已经包含打开特定数据和视图的参数
        let params = this.$route.params;

        if (Object.keys(params).length > 0 && params.uid && params.view) {
            this.openDataView(params.uid, params.view);
        }

        Bus.$off('close');
        Bus.$on('close', ()=>{
            this.openUpload = false;
        });
    },

    props: {
        orgUid: String
    },

    async mounted () {
        await this.getData( 0 );
        await this.getGroups();
        this.$emit( 'on-view-load' );

        Bus.$on('reset-group', async () => {
            await this.getGroups();
        })

    },

    computed: {

        isListView () {
            return !!(this.view === 'imagery-list-wrapper');
        },

    },
    
    beforeRouteEnter(to, from, next) {
        next(vm => {
        });
    },

    beforeRouteLeave: function(to, from, next) {    
        this.closePreview();
        next();
    },

    directives: {
        focus: {
            componentUpdated: function (el, {value}) {
                if (value) {
                    el.focus();
                }
            }
        }
    },

    methods: {

        open () {

        },

        async getGroups () {

            if (!this.orgUid) {
                return;
            }
            
            let result = await orgAPI.summary(this.orgUid);

            if (result.data.code != 0) {
                this.$message.error('获取群组失败');
                return;
            }

            let data = result.data.data;
            let groups = data.groups;
            let members = data.members; 

            let arr = []

            groups.forEach( n => {

                arr.push({
                    name: n.name,
                    key: n.uid,
                    icon: 'group',
                    count: n.members
                })

            });

            this.groups = [].concat(arr);
        },

    	changeRangeType () {
            if (this.loading || this.isEmpty) return;
            this.view = this.view === 'imagery-list-wrapper' ? 'imagery-tiling-wrapper' : 'imagery-list-wrapper';
    	},

    	changeSortTime () {
            if (this.loading) return;

            this.sortTime = this.sortTime === 'desc' ? 'asc' : 'desc';
            this.getData( 0, true );

    	},

        query () {
            if (this.isLoading) {
                return;
            }

            this.getData( 0, true );
        },

        addMore () {
            if (this.hasNext) {
                this.page +=1;
                this.getData( this.page );
            }
        },

        setCurrentMenu (menu) {
            this.currentMenu = menu;
        },

        /**
         * 获取用户数据
         */
        getData (page = 0, clear) {

            this.page = page;
            this.isLoading = true;

            let params = {
                limit,
                page: page,
                search: this.search,
                timeOrder: this.sortTime
            }

            publicImageryAPI.list(
                params,
                (res) => {

                    if(Number(res.data.code) != 0) {

                        let msg = res.data.msg;

                        if(msg) {
                            this.$message.error(msg);
                        }
                        this.isLoading = false;
                        return;
                    }

                    let data = res.data.data;
                
                    if (clear) {

                        if (data.items.length != 0) {
                            this.dataList = [];
                        } else {
                            this.$message.warning( '未找到相应内容' );
                            this.isLoading = false;
                            return;
                        }
                    }

                    this.isLoading = false;

                    this.dataList = this.dataList.concat(data.items);

                    this.hasNext = data.hasNext;

                    this.isEmpty = !this.dataList.length;

                    //关闭加载界面
                    this.$emit('change-loading',{add: true, key: 'public-imagery'});

                    return;

                },
                (err) => {
                    this.isLoading = false;
                    this.$message.error( '获取数据失败' );
                    return;
                }
            )
        },

        preview (data) {

            this.previewData = data;
            this.openPreview = true;

        },

        closePreview () {
            this.previewData = null;
            this.openPreview = false;
        },

        share (data, name) {

            let shared = data.shareStatus;

            if (shared === 'shared') {
                this.$message.warning('该数据已分享过，无法重复分享');
                return;
            }
            this.shareData = data;
            this.shareDataName = name;
            this.openShare = true;
        },

        closeShare: function() {
            this.shareData = '';
            this.openShare = false;
        },

        store (data) {
            this.$emit('data-store', data);
        },

        // upload () {
        //     this.openUpload = true;
        // },

        remove (data, dataName) {
            
            let uid = data.uid;
            let success = false;

            let promise = this.$confirm(
                `数据删除后不可恢复，确认删除数据“${dataName}”？`,
                '删除',
                {
                    type: 'warning',
                    confirmButtonType: 'danger',
                    confirmButtonText: '删除',
                    // parent: this.$refs.myData,
                    beforeClose: async(action, instance, done) => {

                        if (action === 'confirm') {
                            instance.confirmButtonLoading = true;
                            instance.confirmButtonText = '删除中...';
                            instance.cancelButtonDisabled = true;

                            // let result = await bookmarkAPI.getStored(uid);
                            // if (result && result.data.code === 0) {
                            //     let data = result.data.data;
                            //     let stored = data.bookmarks;
                            //     Bus.$emit('clear-bookmark-data', stored);
                            // }
                            

                            let removeResult =await publicImageryAPI.remove(uid);
                            if (removeResult && removeResult.data.code === 0) {
                                    success = true;
                                    Bus.$emit('summary-reset');
                                    // Bus.$emit('group-data-reset');
                                    done();
                            }else{
                                this.$message.error('删除失败');
                                done();
                                return;                            
                            }

                            instance.confirmButtonLoading = false;

                        } else {
                            done();
                        }

                    }
                }
            );

            promise.then(async () => {

                if (!success) {
                    this.$message.error('删除失败');
                    return;
                }
                let dataList = this.dataList;
                let index = dataList.findIndex( item => {
                    return item.uid == uid;
                })

                if (index >= 0) {
                    dataList.splice( index, 1 );
                    this.$message.success('删除成功');

                    let len = dataList.length;

                    if (len === 0 && !this.hasNext) {
                        this.isEmpty = true;
                        return;
                    }

                    if (len === 0 && this.hasNext) {
                        this.getData( 0 );
                    }
                }

                // Bus.$emit('clear-bookmark-count');

            }).catch(() => {
                // this.$message.error('取消')
            })
        },

        async openDataView (uid, viewType) {

            // 获取数据详情
            let dataInfo = await this.getDataInfo(uid);

            if (!dataInfo) {
                return;
            }

            if (viewTypes.indexOf(viewType) === -1) {
                viewType = 'map';
            }

            let customPreviewData = {
                uid: uid,
                // geometryType: dataInfo.type,
                type: dataInfo.type,
                extent: dataInfo.extent,
                name: dataInfo.name,
                count: dataInfo.count,
                view: viewType,
                // convertEnd: dataInfo.geomType === null ? false : true,
                isPrivate: false,
            };

            // 打开预览窗口
            this.openPreview = true;
            this.previewData = customPreviewData;

        },

        /**
         * 获取数据详情
         * @param string uid 数据UID
         */
        async getDataInfo (uid) {

            let dataInfo = await publicImageryAPI.info(uid);

            if (dataInfo.data.code === 0) {
                return dataInfo.data.data;
            }

            this.$message.error('您请求的数据不存在');

            return null;

        }

    }
}
</script>

<style lang="scss" rel="stylesheet/scss" scoped>

    @import "common";

    @media screen and (max-width: 1200px) {
        
        .upload-data {
            
            width: 64px !important;

            > span {
                display: none !important;
            }

            > i {
                display: block !important;
            }
        }
    }

    @media screen and (max-width: 900px) {
        .search {
            display: none !important;
        }
    }

    .public-imagry{
        height: 100%;
        width: 100%;
        font-size: 12px;
        position: relative;
        @include box-sizing(border-box);

    //     .list-table-wrapper{
           
    //         @media screen and (max-width: 1050px) {
    //            	min-width: 720px;
				// -ms-overflow-style: -ms-autohiding-scrollbar;
				// -webkit-overflow-scrolling: touch;
    //         }

    //     }

        >.option{

            width: 100%;
            position: absolute;
            top: 0;
            padding: 18px 0;
            @include box-shadow(0 4px 6px 2px rgba(255, 255, 255, 0.3));

            .option-container {

                overflow: hidden;

                .range{
                    display: block;
                    float: right;
                    width: 160px;
                    color: $gray;
                    padding: 6px 0;
                    cursor: pointer;
                    text-align: right;
                    @include user-select(none);
                    >span{
                        line-heigth: 32px;
                        height: 32px;
                        text-align: center;
                        font-size: 14px;
                        padding: 0 5px;

                        &:hover {
                            color: $primary;
                        }
                    }
                }

                .search{
                    float: right;
                    width: 210px;
                    color: $gray;
                    position: relative;

                    .input-search{
                        width: 210px;
                        height: 32px;
                        padding: 6px 42px 6px 12px;
                        border: 1px solid $bdGray;
                        border-radius: 16px;

                        &:focus {
                            border-color: $info;
                        }
                    }

                    .btn-search{
                        width: 32px;
                        height: 32px;
                        text-align: center;
                        line-height: 32px;
                        cursor: pointer;
                        position: absolute;
                        right: 6px;
                        top: 0;

                        >i {
                            font-size: 14px;
                        }

                        &:hover{
                            color: $primary;
                        }
                    }
                }
            }
        }
    }

    .upload-data{
        height: 32px;
        line-height: 30px;
        width: 90px;
        border-radius: 3px;
        color: $white;
        text-align: center;
        float: left;
        background-color: $primary;
        cursor: pointer;

        &:hover {
            background-color: $darkPrimary;
            font-weight: 500;
        }

        > i {
            font-size: 18px;
            line-height: 30px;
            font-weight: 500;
            display: none;
        }
    }

    @include keyframes(icon-spin){
        from {
            @include rotate(0)
        }
        to {
            @include rotate(359)
        }
    }

</style>
